import { defineStore } from "pinia";
 
import { getStore, removeStore, setStore,removeItemAll } from '@/utils/store'
import { encryption } from "@/utils/util";
import { enCodeKey } from "@/const/const"
import { loginByUsername, codeLogin,refreshToken } from "@/api/login";
import warterMark from "@/utils/waterMark"

const useUserInfoStore = defineStore("userInfo", {
  state: () => ({
    userInfo:getStore({ name: "userInfo" }) || {},
    tenantInfo:getStore({ name: 'tenantInfo' }),
    access_token:getStore({ name: 'access_token' }) ||'',
    refresh_token:getStore({ name: 'refresh_token' }) ||'',
    tenantId:getStore({ name: 'tenantId' }) || '',
    jti:getStore({ name: 'jti' }) || '',
    expires_in:getStore({ name: "expires_in" }) || "",
    roles:getStore({ name: "roles" }) || [],
    permissions: getStore({ name: "permissions" }) || [],
    switchTenant: getStore({ name: "switchTenant" }) || false,
  }),
  getters: {
    getAccessToken:(state)=>{
        return state.access_token
    }
  },
  actions: {
    LoginByUsername(userInfo){
        let user = encryption({
            data: userInfo,
            key: enCodeKey, // "ZnJhbWVmcmFtZQ==",
            param: ["password"]
        });
        user.call_back_url = encodeURIComponent(decodeURIComponent(user.call_back_url))
        return new Promise((resolve,reject)=>{
            if (user.loginType === "namepass") {
                loginByUsername(
                  user.username,
                  user.password,
                  user.code,
                  user.randomStr,
                  user.app_client_id,
                  user.call_back_url
                )
                  .then(response => {
                    const data = response.data;
                    // this.jti = data.jti
                    this.batchSetStore(data)
                    resolve(data);
                  })
                  .catch(error => {
                    reject(error);
                  });
              } else if (user.loginType === "phone") {
                let queryData = {}
                if(userInfo.app_client_id) {
                  queryData.app_client_id = userInfo.app_client_id
                }
                if(userInfo.call_back_url) {
                  queryData.call_back_url = userInfo.call_back_url
                }
                let tp = {
                  data: JSON.stringify(Object.assign({ phone: user.phone, code: user.code }, queryData))
                }
                let temp = encryption({
                  data: tp,
                  key: enCodeKey,
                  param: ["data"]
                });
                codeLogin(('phone@'+temp.data))
                  .then(response => {
                    const data = response.data;
                    this.batchSetStore(data)
                    resolve(data);
                  })
                  .catch(error => {
                    // console.log(error);
                    reject(error);
                  });
              }else if(['invite', 'weixin', 'DINGTALK_INSIDE', 'DINGTALK_SCAN', 'LDAP', 'OWN', 'STANDARD_OWN'].indexOf(userInfo.loginType) > -1) {
                let userTempData = JSON.parse(JSON.stringify(userInfo))
                let spiteIcon = 'invite@'
                if(userInfo.loginType == 'weixin') {
                  spiteIcon = (userTempData.type + '@')
                }
                if(['DINGTALK_INSIDE', 'DINGTALK_SCAN', 'LDAP', 'OWN', 'STANDARD_OWN'].indexOf(userInfo.loginType) > -1) {
                  spiteIcon = (userTempData.loginType + '@')
                }
                delete userTempData.loginType
                let queryData = {}
                if(userInfo.app_client_id) {
                  queryData.app_client_id = userInfo.app_client_id
                }
                if(userInfo.call_back_url) {
                  queryData.call_back_url = userInfo.call_back_url
                }
                let tp = {
                  data: JSON.stringify(Object.assign(userTempData, queryData))
                }
                let temp = encryption({
                  data: tp,
                  key: enCodeKey,
                  param: ["data"]
                });
      
                codeLogin((spiteIcon+temp.data)).then(response => {
                  const data = response.data;
                  this.batchSetStore(data)
                  resolve(data);
                })
                .catch(error => {
                  // console.log(error);
                  reject(error);
                });
              }else if(userInfo.loginType == 'register') {
                let tp = {
                  data: JSON.stringify({ realName: user.username, phone: user.phone, code: user.code })
                }
                let temp = encryption({
                  data: tp,
                  key: enCodeKey,
                  param: ["data"]
                });
                codeLogin(('register@'+temp.data)).then(response => {
                    const data = response.data;
                    this.batchSetStore(data)
                    resolve(data);
                })
                .catch(error => {
                  // console.log(error);
                  reject(error);
                });
              }else{
                if(userInfo.login_other_auth_parameter) {
                  codeLogin(userInfo.login_other_auth_parameter).then(response => {
                    const data = response.data;
                    this.batchSetStore(data)
                    resolve(data);
                  })
                  .catch(error => {
                    // console.log(error);
                    reject(error);
                  });
                }else{
                  if(userInfo.loginType) {
                    let userTempData = JSON.parse(JSON.stringify(userInfo))
                    let spiteIcon = userTempData.loginType + '@'
                    delete userTempData.loginType
                    let queryData = {}
                    if(userInfo.app_client_id) {
                      queryData.app_client_id = userInfo.app_client_id
                    }
                    if(userInfo.call_back_url) {
                      queryData.call_back_url = userInfo.call_back_url
                    }
                    let tp = {
                      data: JSON.stringify(Object.assign(userTempData, queryData))
                    }
                    let temp = encryption({
                      data: tp,
                      key: enCodeKey,
                      param: ["data"]
                    });
                    codeLogin((spiteIcon+temp.data)).then(response => {
                        const data = response.data;
                        this.batchSetStore(data)
                        resolve(data);
                    })
                    .catch(error => {
                      // console.log(error);
                      reject(error);
                    });
                  }
                }
              }
        })
    },
    refreshToken(id){
      return new Promise((resolve, reject) => {
        refreshToken(this.refresh_token, id)
          .then(response => {
            const data = response.data;
            if(data && data.access_token){
              this.batchSetStore(data,['access_token','refresh_token','expires_in'])
              this.setUserInfo(data.userDto)
              this.setTenantId(id)
            }
            resolve(data);
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    LogOut(){
      return new Promise((resolve,reject) =>{
        try {
          let data = {
            "access_token":'',
            "expires_in":'',
            "refresh_token":'',
            "userInfo":{},
            "permissions":[],
            "roles":[],
          }
          this.batchSetStore(data)
          this.setTenantId('')
          warterMark.clear() //退出清空水印
          removeItemAll(['lib','allType','iconList','isMobile'])
          var date=new Date();
          date.setTime(date.getTime()-10000);
          var keys=document.cookie.match(/[^ =;]+(?=\=)/g);
          if (keys) {
            for (var i =  keys.length; i--;)
            document.cookie=keys[i]+"=; expire="+date.toGMTString()+"; path=/";
          }
          resolve();
        } catch (error) {
          reject(error);
        }
      })
    },
    setTenantId(id){
      this.tenantId = id;
      setStore({
        name: "tenantId",
        content: id,
        type: "session"
      });
      setStore({
        name: "tenantId",
        content: id,
        type: ""
      });
    },
    setSwitchTenant(val){
        this.switchTenant = val
        setStore({
            name: "switchTenant",
            content: this.switchTenant,
            type: "session"
        });
    },
    setTenantInfo(info) {
        this.tenantInfo = info;
        setStore({
            name: "tenantInfo",
            content: this.tenantInfo,
            type: "session"
        });
        if(info.icon) {
          var link = document.createElement('link')
          link.type = 'image/x-icon'
          link.rel = 'shortcut icon'
          link.href = info.icon
          document.getElementsByTagName('head')[0].appendChild(link);
        }
        if(info.systemName){
          document.title = info.systemName
        }else{
          document.title = info.shortName || info.name || info.systemName || "无忧 - 企业文档"
        }
    },
    batchSetStore(data,key=['access_token','expires_in','refresh_token','userInfo','roles','permissions'],name){
        this.access_token = data.access_token
        this.refresh_token = data.refresh_token
        this.expires_in = data.expires_in
        this.roles = data.roles || []
        this.permissions = data.permissions || []
        key.forEach(item=>{
            let prop = item
            if(item=='userInfo'){
                prop = 'userDto'
                data.userDto && this.setUserInfo(data.userDto)
            }else{
              setStore({name: item ,content: data[prop],type: "session"});
              setStore({name: item,content: data[prop],type: ""});
            }
            
        })
    },
    setUserInfo(data){
      this.userInfo = data
      setStore({name: 'userInfo' ,content: data,type: "session"});
      setStore({name: 'userInfo',content: data,type: ""});
      // 登录的时候获取随机的UUID 用于编辑器id的链接
      let getUUId = ()=>{
          return URL.createObjectURL(new Blob()).substr(-36)
      }
      setStore({name: "editorId",content: getUUId(),type: ""});
      if(this.userInfo.realName || this.userInfo.accountName) {
          warterMark.set(this.userInfo.realName || this.userInfo.accountName)
      }
    }
  },
});
export default useUserInfoStore;